import { Button, Card, Popconfirm, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import departmentService from '@/api/services/security/departmentService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';

import { DepartmentModal } from './department-modal';
import handleDepartmentData from './handleDepartmentData';
import { DepartmentType } from './modal';

import { ModalProps } from '#/entity';

export default function Department() {
  const [tableData, setTableData] = useState<DepartmentType[]>([]);
  const getList = () => {
    departmentService.getDepartmentsList().then((res) => {
      handleDepartmentData(res);
      setTableData(res);
    });
  };
  useEffect(() => {
    if (hasPermission('DEPARTMENT:DEPARTMENT:READ')) {
      getList();
    }
  }, []);

  const columns: ColumnsType<DepartmentType> = [
    {
      fixed: 'left',
      align: 'center',
      title: '部门名称',
      dataIndex: 'name',
      width: 200,
    },

    {
      title: '部门编码',
      dataIndex: 'code',
    },
    {
      title: '路径',
      dataIndex: 'path',
    },
    {
      title: '深度',
      dataIndex: 'depth',
    },
    {
      title: '部门ID',
      dataIndex: 'id',
    },
    {
      title: '父级ID',
      dataIndex: 'parentId',
    },
    {
      title: '下级数量',
      dataIndex: 'departmentCount',
    },
    {
      title: '直接用户数量',
      dataIndex: 'directUserCount',
    },
    {
      title: '递归用户数(下级所有用户数)',
      dataIndex: 'recursiveUserCount',
    },

    {
      title: '创建时间',
      dataIndex: 'createAt',
      render: (value) => {
        return datetime(value);
      },
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: (value) => {
        return value?.name;
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateAt',
      render: (value) => {
        return datetime(value);
      },
    },
    {
      title: '修改人',
      dataIndex: 'updateBy',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      align: 'center',
      fixed: 'right',
      title: '操作',
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <div className="flex w-full justify-center text-gray">
          {hasPermission('DEPARTMENT:DEPARTMENT:CREATE') && (
            <TipIconButton
              tipText={`为${record.name}新增部门`}
              onClick={() => onItemCreate(record)}
            >
              <Iconify icon="gridicons:add-outline" size={18} />
            </TipIconButton>
          )}
          {hasPermission('DEPARTMENT:DEPARTMENT:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText={`修改${record.name}`}>
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('DEPARTMENT:DEPARTMENT:DELETE') && (
            <Popconfirm
              title={`确定要删除${record.name}吗？删除操作将删除${record.name}及其以下的所有部门`}
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onDelete(record);
              }}
              placement="left"
            >
              <TipIconButton tipText={`删除${record.name}`}>
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];
  const [departmentProps, setDepartmentProps] = useState<ModalProps<DepartmentType>>({
    title: '新增部门',
    show: false,
    formValue: {
      id: undefined,
      name: undefined,
      code: undefined,
      parentId: undefined,
    },
    onOk: () => {
      setDepartmentProps((prev) => ({ ...prev, show: false }));
      getList();
    },
    onCancel: () => {
      setDepartmentProps((prev) => ({ ...prev, show: false }));
    },
  });
  const onCreate = () => {
    setDepartmentProps((prev) => ({
      ...prev,
      title: '新增部门',
      formValue: { name: undefined, parent_id: undefined, tableData },
      show: true,
    }));
  };
  const onItemCreate = (record: DepartmentType) => {
    setDepartmentProps((prev) => ({
      ...prev,
      title: '新增部门',
      show: true,
      formValue: { name: undefined, parent: { id: record.id }, tableData },
    }));
  };
  const onEdit = (record: DepartmentType) => {
    setDepartmentProps((prev) => ({
      ...prev,
      title: '修改部门',
      show: true,
      formValue: { ...record, parent: { id: record.parentId }, tableData },
    }));
  };
  const onDelete = (record) => {
    departmentService.deleteDepartment(record.id).then(() => {
      getList();
    });
  };
  return (
    <Card
      title="部门管理"
      extra={
        <div className="flex items-center gap-2">
          {hasPermission('DEPARTMENT:DEPARTMENT:CREATE') && (
            <Button
              type="primary"
              // disabled={!hasPermission('SECURITY:USER:CREATE')}
              onClick={onCreate}
            >
              新增
            </Button>
          )}
        </div>
      }
    >
      <Table
        // expandable={{ defaultExpandedRowKeys: [1] }}// 展开千讯通集团
        rowKey="id"
        size="small"
        scroll={{ x: 'max-content' }}
        pagination={false}
        columns={columns}
        // dataSource={tableData}
        dataSource={tableData}
      />
      <DepartmentModal {...departmentProps} />
    </Card>
  );
}
